<?php


namespace app\common\cachemodel\live;


use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class LiveCouponActiveRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_coupon_active_record';

    protected $cacheModel = 'live.coupon_active';

    public function updateData(int $id, array $data)
    {
        try
        {
            $this->whereIn('id', $id)->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCache($data);
        }
        catch (\Exception $e)
        {
            Log::write("直播间抽奖活动更新失败：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('a.id', $ids);
            } else
            {
                $this->where('a.live_id', $type[0])->order('id', $sortType);
            }

            $data = $this->alias('a')->join('wechat_backup_07_18_14_43_00.live_coupon lc', 'lc.id=a.live_cid')
                ->join('wechatadmin.system_admin_user au', 'a.aid=au.id', 'LEFT')
                ->column('lc.cid,lc.name,lc.img,a.live_id,a.live_record_id,a.user_group_type,a.live_cid,a.total_num,a.send_num,a.time,a.create_time,a.coupon_expire_time,au.username', 'a.id');

            return $data;
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    /**
     * 获取直播间 最新的 发放优惠券活动信息  基础信息
     * @param $liveId
     * @return mixed|null
     * @throws \Exception
     */
    public function getLiveActiveInfo($liveId)
    {
        $activeId = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('new_active_id', $liveId)->setCacheType('string')->getCache([], 'new_active_id');

        if ($activeId)
        {
            return $this->getInfoById($activeId);
        } else
        {
            return null;
        }
    }

    /**
     * 获取 直播间 最新的 发放优惠券活动信息  直播间详情信息
     * @param $liveId
     * @return array|null
     * @throws \Exception
     */
    public function getHomeNewCouponAcitveInfo($liveId)
    {
        $activeInfo = $this->getLiveActiveInfo($liveId);

        $continueSencond = ($activeInfo['time'] * 60 + $activeInfo['create_time']) - time();
        if ($activeInfo && $continueSencond > 0)
        {
            return [
                'id' => $activeInfo['id'],
                'title' => '优惠券',
                'img' => $activeInfo['img'],
                'name' => $activeInfo['name'],
                'is_only_vip_show' => (int)$activeInfo['user_group_type'] === 2 ? 1 : 0,
                'continue_sencond' => $continueSencond
            ];
        } else
        {
            return null;
        }
    }

    /**
     * 缓存 优惠券赠送数量增加
     * @param $id
     * @param int $inc
     * @return int
     * @throws \Exception
     */
    public function CouponSendNumInc($id, $inc = 1): int
    {
        $cache = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id);

        $redis = $cache->redisHandler;

        return $redis->hIncrBy($cache->cacheKey['details'], 'send_num', $inc);
    }

    /**
     * 获取发放优惠券记录
     * @param $liveId
     * @return array|mixed
     * @throws \Exception
     */
    public function getRecordLists($liveId)
    {
        $pageData = $this->getListPage($liveId);

        $resData = [];
        foreach ($pageData['data'] as $datum)
        {
            $resData[] = [
                'id' => $datum['id'],
                'title' => $datum['name'] . '赠送',
                'time' => date('Y-m-d H:i:s', $datum['create_time']),
                'target' => '',
                'link' => '',
            ];
        }

        $pageData['data'] = $resData;

        return $pageData;
    }

    /**
     * 获取优惠券发放记录详情
     */
    public function getRecordDetail($liveId, $id)
    {
        $info = $this->getInfoById($id);

        if (empty($info) || $info['live_id'] != $liveId)
        {
            return null;
        }

        $resData = [
            'common_list' => [
                [
                    'type' => 1,
                    'title' => '赠送详情',
                    'desc' => ''
                ],
                [
                    'type' => 2,
                    'title' => '类型：',
                    'desc' => '优惠券'
                ],
                [
                    'type' => 2,
                    'title' => '名称：',
                    'desc' => $info['name']
                ],
                [
                    'type' => 2,
                    'title' => '开启时间：',
                    'desc' => date('Y-m-d H:i:s', $info['create_time'])
                ],
                [
                    'type' => 2,
                    'title' => '参与人群：',
                    'desc' => $info['user_group_type'] == 1 ? '所有用户' : 'VIP用户'
                ],
                [
                    'type' => 2,
                    'title' => '数量：',
                    'desc' => $info['total_num']
                ],
                [
                    'type' => 2,
                    'title' => '有效时长：',
                    'desc' => $info['coupon_expire_time'] . '天'
                ],
                [
                    'type' => 2,
                    'title' => '领取人数：',
                    'desc' => $info['send_num']
                ],
                [
                    'type' => 2,
                    'title' => '使用率：',
                    'desc' => (new LiveCouponActiveGiveRecord())->getCouponActiveUseRatio($info['id']) . '%'
                ], [
                    'type' => 2,
                    'title' => '操作人：',
                    'desc' => $info['username'] ?? ''
                ]
            ],
        ];

        return $resData;
    }
}
